<template>
  <a-drawer
      :afterVisibleChange="visible=>getInputParamsOptions(visible)"
      :closable="false"
      :title="title"
      :visible="visible"
      :width="width"
      destroyOnClose
      placement="right"
      @close="close"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form" v-if="model.function">
        <a-form-item v-show="false" :labelCol="labelCol" :wrapperCol="wrapperCol" label="模型主键">
          <a-input v-decorator="['function.deviceModelBy', {initialValue: model.function.deviceModelBy, rules: []}]" readOnly></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="功能主键">
          <a-input v-decorator="['function.id', {initialValue: model.function.id, rules: []}]" readOnly></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标识">
          <a-input v-decorator="[ 'function.code', {initialValue: model.function.code, rules: validatorRules.code.rules}]" placeholder="请输入标识"></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="名称">
          <a-input v-decorator="[ 'function.name', {initialValue: model.function.name, rules: validatorRules.name.rules}]" placeholder="请输入名称"></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="功能类型">
          <a-radio-group
            v-decorator="['function.type', {initialValue: model.function.type, rules: validatorRules.type.rules}]"
            @change="val => functionTypeChanged(val.target.value)"
          >
            <a-radio v-for="(type, index) in functionTypeOptions" :key="type.value" :value="type.value">
              {{ type.text }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否同步">
          <a-switch
            v-model="model.function.isSync"
            :disabled="model.function.type!=='found'"
            checkedChildren="同步"
            unCheckedChildren="异步" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="{span:'24'}">
          <a-card :hoverable="true" title="输入参数">
            <template slot="extra">
              <a-button icon="plus" @click="addRowParam"></a-button>
            </template>
            <a-row style="margin-bottom:10px" type="flex">
              <a-col :span="11">
                参数名称
                <a-tooltip>
                  <div slot="title">调用非只读数据节点</div>
                  <a-icon theme="twoTone" type="question-circle-o"/>
                </a-tooltip>
              </a-col>
              <a-col :span="11">
                输入方式
                <a-tooltip>
                  <ui slot="title">
                    <li>多选下拉框：</li>
                    <li>实例注入：输入参数值在设备实例化是动态赋值，前端不能修改</li>
                    <li>前端操作：输入参数值在前端直接赋值</li>
                  </ui>
                  <a-icon theme="twoTone" type="question-circle-o"/>
                </a-tooltip>
              </a-col>
              <a-col :span="2">操作</a-col>
            </a-row>
            <a-empty v-if="model.inputParams.length <= 0" :description="false"/>
            <a-row v-for="(param, index) in model.inputParams" :key="index" :gutter="10" style="margin:0px;" type="flex">
              <a-col :span="11">
                <a-form-item v-show="false" :labelCol="labelCol" :wrapperCol="wrapperCol" label="功能主键">
                  <a-input v-show="true" v-decorator="['inputParams['+index+'].functionId', {initialValue: param.functionId, rules: []}]"></a-input>
                </a-form-item>
                <a-form-item v-show="false" :labelCol="labelCol" :wrapperCol="wrapperCol" label="输入输出">
                  <a-input v-show="true" v-decorator="['inputParams['+index+'].direction', {initialValue: param.direction, rules: []}]"></a-input>
                </a-form-item>
                <a-form-item>
                  <a-select v-decorator="['inputParams['+index+'].dataId',
                                                { initialValue: param.dataId, rules:[{required: true, message: '请选择输入参数'}]}]"
                            :allowClear="true"
                            :options="inputParamsOptions"
                            mode="default"
                            placeholder="请选择输入参数"
                            style="width: 100%"
                  >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="11">
                <a-form-item>
                  <a-select
                    v-decorator="['inputParams['+index+'].inputMode',
                                                { initialValue: param.inputMode, rules:[{required: true, message: '请选择输入方式'}]}]"
                    :allowClear="true"
                    placeholder="请选择输入方式"
                    style="width: 100%"
                  >
                    <a-select-option v-for="option in paramInputModeOptions" :key="option.value">
                      {{ option.text }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-button icon="minus" @click="delRowParam(index)"></a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form-item>
        <a-form-item v-show="model.function.isSync" :labelCol="labelCol" :wrapperCol="wrapperCol" label="返回数据">
          <j-search-select-tag
            v-decorator="['outputData', {rules:[{required: false, message: '请选择返回数据'}]}]"
            :dictOptions="backDataOptions"
            :triggerChange="true"
            placeholder="请输入用户性别"
            type="list" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述">
          <a-textarea v-decorator="['description', validatorRules.description]" allowClear placeholder="请输入描述" rows="3" />
        </a-form-item>

      </a-form>
    </a-spin>

    <div :style="{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
              zIndex: 1,
            }"
    >
      <a-button :style="{ marginRight: '10px' }" type="primary" @click="handleOk">确定</a-button>
      <a-button type="" @click="close">取消</a-button>
    </div>
  </a-drawer>
</template>

<script>
import pick from 'lodash.pick'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import {getAction, httpAction} from '@/api/manage'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'

export default {
  name: 'FuncDrawer',
  components: {
    JSearchSelectTag,
    JDictSelectTag,
    JMultiSelectTag
  },
  props: ['deviceModelId'],
  data() {
    return {
      form: this.$form.createForm(this),
      title: '',
      width: 500,
      visible: false,
      functionTypeOptions: [],
      paramInputModeOptions: [],
      baseModel: {
        modelId: '',
        function: {
          code: '',
          deviceModelBy: '',
          id: '',
          isSync: false,
          name: '',
          type: 'request'
        },
        inputParams: []
        // outputParam: {}
      },
      model: {},
      backDataOptions: [],
      inputParamsOptions: [],
      confirmLoading: false,
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 16
      },
      validatorRules: {
        code: {
          rules: [
            { required: true, message: '请输入标识!' },
            { min: 2, max: 20, message: '标识长度：2-20个字符' },
            {
              validator: (rule, value, callback) => this.validateDuplicateCode(this.model.function.deviceModelBy, this.model.function.id, value, callback)
            }
          ]
        },
        name: {
          rules: [
            { required: true, message: '请输入名称!' },
            { min: 2, max: 20, message: '名称长度：2-20个字符' },
            { validator: (rule, value, callback) => this.validateDuplicateName(this.model.function.deviceModelBy, this.model.function.id, value, callback) }
          ]
        },
        type: { rules: [{ required: true, message: '请选择功能类型!' }] },
        description: { rules: [] }
      },
      url: {
        add: '/device/model/addFunc',
        edit: '/device/model/editFunc',
        getTypes: '/device/model/getFunctionTypes',
        getInputModes: '/device/model/getInputModes',
        validateCode: '/device/model/validateFuncCode',
        validateName: '/device/model/validateFuncName'
      }
    }
  },
  created() {
    this.getSelectOptions()
  },
  mounted() {
    this.getFunctionTypes()
    this.getParamInputMode()
  },
  methods: {
    functionTypeChanged(type) {
      let scope = this
      this.model.function.type = type
      if (type !== 'found') {
        this.model.function.isSync = false
      }
    },
    getParamInputMode() {
      let scope = this
      getAction(this.url.getInputModes).then(res => {
        if (res.success) {
          scope.paramInputModeOptions = res.result
        }
      })
    },
    getFunctionTypes() {
      let scope = this
      getAction(this.url.getTypes).then(res => {
        if (res.success) {
          scope.functionTypeOptions = res.result
        }
      })
    },
    validateDuplicateCode(modelId, funcId = '', funcCode = '', callback) {
      console.log('22222')
      getAction(this.url.validateCode, { deviceModelId: modelId, funcId: funcId, funcCode: funcCode }).then(res => {
        res['success'] ? callback() : callback(res['message'])
      })
    },
    validateDuplicateName(modelId, funcId = '', funcName = '', callback) {
      console.log('5555')
      getAction(this.url.validateName, { deviceModelId: modelId, funcId: funcId, funcName: funcName }).then(res => {
        res['success'] ? callback() : callback(res['message'])
      })
    },
    addRowParam() {
      this.model.inputParams.push({})
      this.$forceUpdate()
    },
    delRowParam(index) {
      console.log(index)
      this.model.inputParams.splice(index, 1)
      this.$forceUpdate()
    },
    close() {
      this.$emit('close')
      this.confirmLoading = false
      this.visible = false
    },
    add(modelId) {
      this.form.resetFields()
      this.model = JSON.parse(JSON.stringify(this.baseModel))
      this.model.modelId = modelId
      this.model.function.deviceModelBy = modelId
      this.visible = true
    },
    edit(record) {
      this.form.resetFields()
      this.model = JSON.parse(JSON.stringify(this.baseModel))
      this.model = Object.assign(this.model, record)
      this.visible = true
      let fields = pick(this.model, 'function', 'inputParams', 'outputData')
      this.$nextTick(() => {
        this.form.setFieldsValue(fields)
      })
      // this.getSelectOptions();
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        console.log(err, values)
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.function.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          // 输入参数的输入方式
          formData.inputParams
            .filter(input => input.inputMode instanceof String)
            .map(input => {
              input.inputMode = Array(input.inputMode)
            })
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method).then((res) => {
            console.log(res)
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }

      })
    },
    getInputParamsOptions(visible) {
      if (!visible) return
      let that = this
      getAction('/sys/dict/getDictItems/iot_device_data,name,id,rw_author!=\'r\' and device_model_by=' + this.deviceModelId, null).then(res => {
        if (res.success) {
          that.inputParamsOptions = res.result
        }
      })
    },
    getSelectOptions() {
      let that = this
      getAction('/sys/dict/getDictItems/iot_device_data,name,id,rw_author!=\'w\' and device_model_by=' + this.deviceModelId, null).then(res => {
        console.log(res)
        if (res.success) {
          that.backDataOptions = res.result
        }
      })
    }
  }

}
</script>

<style lang="less" scoped>

</style>
